package cn.dgiot.fd.service.impl;

import java.sql.Timestamp;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.dgiot.fd.model.MessageFcdy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.iot.model.v20180120.RRpcRequest;
import com.aliyuncs.iot.model.v20180120.RRpcResponse;
import com.aliyuncs.profile.DefaultProfile;

import cn.dgiot.fd.contant.AliyunConfig;
import cn.dgiot.fd.model.InstructionsStatusModel;
import cn.dgiot.fd.model.MessageModel;
import cn.dgiot.fd.service.IAmqpMessageHandler;
import cn.dgiot.fd.service.IInstructionsStatusService;
import cn.dgiot.fd.service.IMessageSendService;

@Service
public class MessageSendServiceImpl implements IMessageSendService {

	private Logger logger = LoggerFactory.getLogger(MessageSendServiceImpl.class);

	@Autowired
	private AliyunConfig aliyunConfig;

	@Autowired
	private IAmqpMessageHandler amqpMessageHandler;

	@Autowired
	private IInstructionsStatusService instructionsStatusService;

	@Override
	@Transactional
	public Map<String, Object> sendMessage(MessageModel messageModel) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String regionId = aliyunConfig.regionId;
		String accessKey = aliyunConfig.accessKey;
		String accessSecret = aliyunConfig.accessSecret;
		final String productKey = aliyunConfig.productKey;
		String deviceName = messageModel.getDeviceName();
		String instructions = messageModel.getInstructions();
		DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);

		RRpcRequest request = new RRpcRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setTimeout(8000);
		// 设置消息的内容，一定要用base64编码，否则乱码。
		request.setRequestBase64Byte(Base64.getEncoder()
				.encodeToString(("{" + "\"key\":\"" + instructions + "\"," + "\"req\":\""
						+ UUID.randomUUID().toString().replace("-", "") + "\"," + "\"date\":\"" + (new Date().getTime())
						+ "\"" + "}").getBytes()));
		// 设置发布消息的topic。
		request.setTopic("/" + productKey + "/" + deviceName + aliyunConfig.rrpcTopic);
		InstructionsStatusModel instantiationStatusModel = new InstructionsStatusModel();
		RRpcResponse response = new RRpcResponse();
		try {
			instantiationStatusModel.setRequestTime(new Timestamp(new Date().getTime()));
			String requestId = UUID.randomUUID().toString().replace("-", "");
			String id = UUID.randomUUID().toString().replace("-", "");
			instantiationStatusModel.setId(id);
			instantiationStatusModel.setRequestId(requestId);
			instantiationStatusModel.setInstructions(instructions);
			response = client.getAcsResponse(request);
			String downstreamData = new String(Base64.getDecoder().decode(response.getPayloadBase64Byte()));
			Timestamp reportTime = new Timestamp(new Date().getTime());
			logger.info("主动下发指令-topic:" + request.getTopic());
			logger.info("主动下发指令-content:" + downstreamData);
			logger.info("主动下发指令-requestId:" + requestId);
			amqpMessageHandler.customTopicHandler(request.getTopic(), downstreamData, requestId);
			if (response.getSuccess()) {
				resultMap.put("requestId", requestId);
				instantiationStatusModel.setJson(downstreamData);
				instantiationStatusModel.setReportStatus("1");
			} else {
				instantiationStatusModel.setReportStatus("0");
			}
			instantiationStatusModel.setReportTime(reportTime);
			logger.info("消息发送成功" + response.getSuccess());
		} catch (Exception e) {
			instantiationStatusModel.setReportStatus("0");
			response.setSuccess(false);
		}
		instructionsStatusService.insertInstructionsStatus(instantiationStatusModel);

		resultMap.put("success", response.getSuccess());
		return resultMap;
	}

	@Override
	public Map<String, Object> sendFcdy(MessageFcdy messageFcdy) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String regionId = aliyunConfig.regionId;
		String accessKey = aliyunConfig.accessKey;
		String accessSecret = aliyunConfig.accessSecret;
		final String productKey = aliyunConfig.productKey;
		String deviceName = messageFcdy.getDeviceName();
		String instructions = messageFcdy.getInstructions();
		String fcdy = messageFcdy.getFcdy();
		DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);

		RRpcRequest request = new RRpcRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setTimeout(8000);
		// 设置消息的内容，一定要用base64编码，否则乱码。
		request.setRequestBase64Byte(Base64.getEncoder()
				.encodeToString(("{" + "\"key\":\"" + instructions + "\"," + "\"fcdy\":\"" + fcdy + "\"," + "\"req\":\""
						+ UUID.randomUUID().toString().replace("-", "") + "\"," + "\"date\":\"" + (new Date().getTime())
						+ "\"" + "}").getBytes()));
		// 设置发布消息的topic。
		request.setTopic("/" + productKey + "/" + deviceName + aliyunConfig.rrpcTopic);
		InstructionsStatusModel instantiationStatusModel = new InstructionsStatusModel();
		RRpcResponse response = new RRpcResponse();
		try {
			instantiationStatusModel.setRequestTime(new Timestamp(new Date().getTime()));
			String requestId = UUID.randomUUID().toString().replace("-", "");
			String id = UUID.randomUUID().toString().replace("-", "");
			instantiationStatusModel.setId(id);
			instantiationStatusModel.setRequestId(requestId);
			instantiationStatusModel.setInstructions(instructions);
			response = client.getAcsResponse(request);
			String downstreamData = new String(Base64.getDecoder().decode(response.getPayloadBase64Byte()));
			Timestamp reportTime = new Timestamp(new Date().getTime());
			logger.info("主动下发指令-topic:" + request.getTopic());
			logger.info("主动下发指令-content:" + downstreamData);
			logger.info("主动下发指令-requestId:" + requestId);
			amqpMessageHandler.customTopicHandler(request.getTopic(), downstreamData, requestId);
			if (response.getSuccess()) {
				resultMap.put("requestId", requestId);
				instantiationStatusModel.setJson(downstreamData);
				instantiationStatusModel.setReportStatus("1");
			} else {
				instantiationStatusModel.setReportStatus("0");
			}
			instantiationStatusModel.setReportTime(reportTime);
			logger.info("消息发送成功" + response.getSuccess());
		} catch (Exception e) {
			instantiationStatusModel.setReportStatus("0");
			response.setSuccess(false);
		}
		instructionsStatusService.insertInstructionsStatus(instantiationStatusModel);

		resultMap.put("success", response.getSuccess());
		return resultMap;
	}

}
